package cn.edu.zafu.bigdata.zyf;

import java.io.*;
import java.net.*;

public class TimeClient {
    public static void main(String[] args) {
        String hostname = "localhost"; // 服务端的主机名或IP地址
        int port = 1234; // 服务端监听的端口

        try (DatagramSocket socket = new DatagramSocket()) {
            System.out.println("Time client is running...");

            String sentence = "Current time, please?";
            byte[] sendData = sentence.getBytes();
            byte[] receiveData = new byte[1024];

            InetAddress address = InetAddress.getByName(hostname);

            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
            socket.send(sendPacket);

            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);

            String output = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Time server says: " + output);
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostname);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}